package nl.windgazer.arachne.components;

import java.util.ArrayList;

import nl.windgazer.arachne.services.LanguageVO;

import org.apache.log4j.Logger;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.ActionLink;
import org.apache.tapestry5.corelib.components.Loop;
import org.apache.tapestry5.internal.util.LocaleUtils;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.SymbolSource;
import org.apache.tapestry5.ioc.services.ThreadLocale;
import org.apache.tapestry5.services.PersistentLocale;

public class LanguageSwitch {

	private Logger logger = Logger.getLogger(LanguageSwitch.class);

	//Injects and Persists

	@Inject
	private ThreadLocale _tLocale;

	@Inject
	private SymbolSource _symbols;

	@Inject
	private PersistentLocale _locale;

	@Inject
	private Messages _msgs;
	
	//Properties and Parameters
	@Parameter(principal=true, required=false, defaultPrefix=BindingConstants.PROP)
	private boolean renders = false;

	@Property
	private final ArrayList<LanguageVO> validLocales = new ArrayList<LanguageVO>();

	@SuppressWarnings("unused")
	@Property
	private LanguageVO lang;

	//Components

	@SuppressWarnings("unused")
	@Component(id = "langLoop", parameters = { "source=validLocales",
			"value=lang" })
	private Loop _langLoop;

	@SuppressWarnings("unused")
	@Component(id = "langLink", parameters = {"context=prop:langUid"})
	private ActionLink _langLinkComponent;

	//Events

	@SetupRender
	boolean checkLocales() {
		final String sLocales = _symbols.valueForSymbol(SymbolConstants.SUPPORTED_LOCALES);
		if (validLocales.size()<=0 && sLocales != null) {
			final String[] slLocales = sLocales.split(",");
			if (slLocales.length < 2) { //Don't render with only a single supported locale
				renders = false;
			} else {
				renders = true;
				for (final String sLocale : slLocales) {
					try {
						validLocales.add(new LanguageVO(LocaleUtils.toLocale(sLocale)));
					} catch (java.lang.IllegalArgumentException e) {
						logger.error(e);
					}
				}
			}
		} else if (validLocales.size() > 0) {
			renders = true;
		}
		return renders;
	}

	@OnEvent(component="langLink", value=EventConstants.ACTION)
	void setPersistentLocale(String sLocale) {
		_locale.set(LocaleUtils.toLocale(sLocale));
	}

	//Other (check for business-logic, it should not remain here)

	public String getLangUid() {
		return lang.toString();
	}

	public boolean isCurrent() {
		return _tLocale.getLocale().equals(lang.getLocale());
	}

	public String getLanguageTitle() {
		return _msgs.get(lang.getKey());
	}

}
